package com.xue.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.xue.bean.User;
import com.xue.service.IUserService;
import com.xue.service.RedisService;
import com.xue.util.MyException;
import com.xue.util.UUIDUtil;
import com.xue.vo.LoginVo;

@Service
public class UserServiceImpl implements IUserService{
	
	 public static final String COOKIE_NAME_TOKEN = "token";
	 
	 
	@Autowired
    private RedisService redisUtil;
	
	public User getById(String id) {
        //对象缓存
		User user = redisUtil.get(id,User.class);
//		User user = redisUtil.hget(UserKey.getById, "" + id, User.class);
        if (user != null) {
        	System.err.println("redis取:"+user.toString());
            return user;
        }
//        //取数据库
//        user = userMapper.getById(id);
        user = new User();
        user.setUserId(id);
        user.setUserName("小娜");
        user.setUserAge("22");
        user.setUserSex("女");
        user.setUserTel("15966332233");
        
//        //再存入缓存
        if (user != null) {
        	redisUtil.set(id, user ,20);
        	System.err.println("redis存:"+user.toString());
        }
        return user;
    }
	
	@Override
	public String login(HttpServletResponse response, LoginVo loginVo) {
		if (loginVo == null) {
            try {
				throw new MyException("请输入用户名和密码");
			} catch (MyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        String userId = loginVo.getUserId();
        String formPass = loginVo.getPassword();
       
        
        //判断手机号是否存在
        User user = getById(userId);
//        if (user == null) {
//            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
//        }
//        //验证密码
//        String dbPass = user.getPassword();
//        String saltDB = user.getSalt();
//        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
//        if (!calcPass.equals(dbPass)) {
//            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
//        }
//        //生成唯一id作为token
        String token = UUIDUtil.uuid();
        System.out.println("token:"+token);
        addCookie(response, token, user);
        return token;
	}
	
	
	/**
     * 	将token做为key，用户信息做为value 存入redis模拟session
     * 	同时将token存入cookie，保存登录状态
     */
    public void addCookie(HttpServletResponse response, String token, User user) {
    	redisUtil.set(token,  user , 30);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(30);
        cookie.setPath("/");//设置为网站根目录
        response.addCookie(cookie);
    }

    /**
     * 	根据token获取用户信息
     */
    public User getByToken(HttpServletResponse response, String token) {
        
    	if (StringUtils.isEmpty(token)) {
            return null;
        }
        User user = redisUtil.get(token,  User.class);
        //延长有效期，有效期等于最后一次操作+有效期
        if (user != null) {
            addCookie(response, token, user);
        }
        return user;
    }
    /**
     * 	刷新token
     */
	@Override
	public boolean setToken(HttpServletResponse response, String token) {
		redisUtil.setExpire(token, 30);
		
		return true;
	}
    
}
